<?php


namespace app\admin\service\base;


use app\admin\model\base\Paper;
use app\admin\model\base\Special;
use app\admin\model\base\Student;
use app\admin\model\base\StudentPaper;
use app\admin\model\base\StudentPaperSubject;
use app\BaseService;
use think\response\Json;

class StudentPaperService extends BaseService
{
    /**
     * 学生考试列表
     * @param array $params
     * @return Json
     */
    public function index(array $params): Json
    {
        $where = [];
        if(isset($params['paper_id']) && $params['paper_id']){
            $where[] = ['paper_id','=',$params['paper_id']];
        }
        if(isset($params['realname']) && $params['realname']){
            //查询学生姓名
            $ids = ['999999999'];
            $nameList = Student::where('realname','like',"%{$params['realname']}%")->select()->toArray();
            if(!empty($nameList)){
                $ids = array_column($nameList,'id');
            }
            $where[] = ['student_id','in',implode(',',$ids)];
        }
        if(isset($params['name']) && $params['name']){
            //查询学生姓名
            $idss = ['999999999'];
            $namesList = Paper::where('name','like',"%{$params['name']}%")->select()->toArray();
            if(!empty($namesList)){
                $idss = array_column($namesList,'id');
            }
            $where[] = ['paper_id','in',implode(',',$idss)];
        }

        if(isset($params['scoring']) && $params['scoring'] != ''){
            if($params['scoring'] == 2 && isset($params['paper_id']) && $params['paper_id']){
                //查询未参加考试的学生
                $info = Paper::findOne(['id'=>$params['paper_id']]);
                $id = [0];
                if($info){
                    $list = StudentPaper::where('paper_id','=',$params['paper_id'])->select()->toArray();
                    $id = json_decode($info['student'],true);
                    if(!empty($list)){
                        $ids = array_column($list,'student_id');
                        $id = array_diff($id,$ids);
                    }
                }
                $list = Student::where('id','in',implode(',',$id))
                    ->with(['grades','classes','special'])
                    ->field('id,realname,sex,username,grades_id,classes_id,special_id')
                    ->paginate(['list_rows' => $params['limit'] ?? 100, 'page' => $params['page'] ?? 1], false)
                    ->toArray();
                return jsonReturn(1, $list);
            }
            $where[] = ['scoring','=',$params['scoring']];
        }

        if(isset($params['status']) && $params['status'] != ''){
            $where[] = ['status','=',$params['status']];
        }
        //获取列表
        $data = StudentPaper::getList($where, $params['page'] ?? 1, $params['limit'] ?? 100, 'id desc');
        return jsonReturn(1, $data);
    }

    /**
     * 试卷列表
     * @param array $params
     * @return Json
     */
    public function index2(array $params): Json
    {
        $where = [];
        $where[] = ['is_release','=',1];
        $where[] = ['is_del','=',0];
        //获取列表
        $data =  Paper::getList2($where, $params['page'] ?? 1, $params['limit'] ?? 100, 'id desc');
        return jsonReturn(1, $data);
    }

    /**
     * 打分
     * @param array $params
     * @return Json
     */
    public function scoring(array $params):Json
    {
        if(!isset($params['id'])){
            return jsonReturn(0, [],'请选择要打分的试卷');
        }
        if(!isset($params['list'])){
            return jsonReturn(0, [],'请选择要打分的题目');
        }
        if(!intval($params['id'])){
            return jsonReturn(0, [],'试卷选择错误');
        }
        if(empty($params['list'])){
            return jsonReturn(0, [],'请选择要打分题目');
        }
        $infos = StudentPaper::where('id','=',$params['id'])->find();
        if(!$infos) return jsonReturn(0, [],'试卷不存在');
        if($infos->status != 1) return jsonReturn(0, [],'学生未交卷');

        $arr = [];
        $list = $params['list'];
        $num = 0;
        $score = 0;
        foreach ($list as $value){
            $data = [
                'score'=>0,
                'id'=>$value['id'],
                'is_score'=>0
            ];
            if($value['score'] != ''){
                $num = $num + 1;
                $score = $score + $value['score'];
                $data['score'] = $value['score'];
                $data['is_score'] = 1;
            }
            $arr[] = $data;
        }
        \think\facade\Db::startTrans();
        try {
            $model = new StudentPaperSubject();
            $model2 = new StudentPaper();
            if(!empty($arr)){
                $res = $model->saveAll($arr);
                if(!$res){
                    throw new \Exception('打分失败');
                }
                $data2 = ['score'=>$score];
                if(count($list) == $num){
                    //判分完毕，试卷状态修改未已判分
                    $data2['scoring'] = 1;
                }
                $data2['scoring_time'] = date('Y-m-d H:i:s',time());
                $data2['create_user'] = WS_ADMIN_ID;
                $res2 = $model2->where('id','=',$params['id'])->update($data2);
                if(!$res2){
                    throw new \Exception('更新试卷失败');
                }
            }
            \think\facade\Db::commit();
            return jsonReturn(1, ['score'=>$score],'打分成功');
        }catch (\Exception $exception){
            \think\facade\Db::rollback();
            return jsonReturn(0, [],$exception->getMessage());
        }
    }

    /**
     * 试卷绑定学生
     * @param array $params
     * @return Json
     */
    public function binding(array $params):Json
    {
        if(!$params['id']) return jsonReturn(0, [],'参数错误');
        if(!isset($params['ids'])) return jsonReturn(0, [],'请选择学生');
        if(empty($params['ids'])) return jsonReturn(0, [],'请选择学生');
        $infos = Paper::where('id','=',$params['id'])->find();
        if(!$infos){
            return jsonReturn(0, [],'失败');
        }

//        if($infos['is_release'] == 1) return jsonReturn(0, [],'试卷已发布');

        $arr = $params['ids'];
//        if(!empty($arr)){
//            foreach ($arr as $value){
//
//            }
//        }
        if(is_string($infos->student)){
//            $st = json_decode($infos->student);
//            $arr = array_merge($st,$arr);
//            $arr = array_keys(array_flip($arr));
//            $arr = array_unique($arr);
        }
        $infos->student = json_encode($arr);
        $res = $infos->save();
        if(!$res) return jsonReturn(0, [],'保存失败');
        return jsonReturn(1, []);
    }

    /**
     * 打分
     * @param array $params
     * @return Json
     */
    public function read(array $params):Json
    {
        $info = StudentPaper::where('id','=',$params['id'])->with(['student_paper_subject','paper'])->find();
        return jsonReturn(1, $info);
    }

}